package cn.tedu.tmall.front.account.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.front.account.dao.persist.repository.IUserRepository;
import cn.tedu.tmall.front.account.pojo.entity.User;
import cn.tedu.tmall.front.account.pojo.param.UserRegisterParam;
import cn.tedu.tmall.front.account.pojo.param.UserUpdateInfoParam;
import cn.tedu.tmall.front.account.pojo.vo.UserSimpleInfoVO;
import cn.tedu.tmall.front.account.pojo.vo.UserStandardVO;
import cn.tedu.tmall.front.account.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 处理用户数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserServiceImpl() {
        log.debug("创建业务类对象：UserServiceImpl");
    }

    @Override
    public void register(UserRegisterParam userRegisterParam) {
        log.debug("开始处理【用户注册】的业务，参数：{}", userRegisterParam);

        // 检查用户名是否被占用
        {
            String username = userRegisterParam.getUsername();
            int count = userRepository.countByUsername(username);
            if (count > 0) {
                String message = "添加用户失败，用户名已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 检查手机号码是否被占用
        {
            String phone = userRegisterParam.getPhone();
            int count = userRepository.countByPhone(phone);
            if (count > 0) {
                String message = "添加用户失败，手机号码已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 检查电子邮箱是否被占用
        {
            String email = userRegisterParam.getEmail();
            int count = userRepository.countByEmail(email);
            if (count > 0) {
                String message = "添加用户失败，电子邮箱已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        User user = new User();
        BeanUtils.copyProperties(userRegisterParam, user);
        user.setLoginCount(0);
        user.setEnable(ENABLE_STATE_ON);
        String rawPassword = user.getPassword();
        String encodedPassword = passwordEncoder.encode(rawPassword);
        user.setPassword(encodedPassword);
        int rows = userRepository.insert(user);
        if (rows != 1) {
            String message = "注册失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void updateInfo(CurrentPrincipal currentPrincipal, UserUpdateInfoParam userUpdateInfoParam) {
        log.debug("开始处理【修改基本信息】的业务，当事人：{}，新基本信息：{}", currentPrincipal, userUpdateInfoParam);
        Long userId = currentPrincipal.getId();
        User user = new User();
        BeanUtils.copyProperties(userUpdateInfoParam, user);
        user.setId(userId);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改基本信息失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updatePassword(CurrentPrincipal currentPrincipal, String oldPassword, String newPassword) {
        log.debug("开始处理【修改密码】的业务，当事人：{}，原密码：{}，新密码：{}", currentPrincipal, oldPassword, newPassword);
        Long userId = currentPrincipal.getId();
        UserStandardVO queryResult = userRepository.getStandardById(userId);
        String dbPassword = queryResult.getPassword();
        boolean matches = passwordEncoder.matches(oldPassword, dbPassword);
        if (!matches) {
            String message = "修改密码失败，原密码错误！";
            log.warn(message);
            log.trace("用户提交的原密码：{}", oldPassword);
            log.trace("数据库中的密文：{}", dbPassword);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        String encodedPassword = passwordEncoder.encode(newPassword);
        User user = new User();
        user.setId(userId);
        user.setPassword(encodedPassword);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改密码失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateAvatar(CurrentPrincipal currentPrincipal, String avatar) {
        log.debug("开始处理【修改头像】的业务，当事人：{}，新头像：{}", currentPrincipal, avatar);
        Long userId = currentPrincipal.getId();
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatar);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改头像失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updatePhone(CurrentPrincipal currentPrincipal, String phone) {
        log.debug("开始处理【修改手机号码】的业务，当事人：{}，新手机号码：{}", currentPrincipal, phone);
        Long userId = currentPrincipal.getId();
        int count = userRepository.countByPhoneAndNotId(phone, userId);
        if (count > 0) {
            String message = "修改手机号码失败，手机号码已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(userId);
        user.setPhone(phone);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改手机号码失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateEmail(CurrentPrincipal currentPrincipal, String email) {
        log.debug("开始处理【修改电子邮箱】的业务，当事人：{}，新手机号码：{}", currentPrincipal, email);
        Long userId = currentPrincipal.getId();
        int count = userRepository.countByEmailAndNotId(email, userId);
        if (count > 0) {
            String message = "修改电子邮箱失败，电子邮箱已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(userId);
        user.setEmail(email);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改电子邮箱失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public UserSimpleInfoVO getSelfSimpleInfo(CurrentPrincipal currentPrincipal) {
        log.debug("开始处理【查询当前用户基本信息】的业务，当事人：{}", currentPrincipal);
        Long userId = currentPrincipal.getId();
        UserSimpleInfoVO queryResult = userRepository.getSimpleInfoById(userId);
        if (queryResult == null) {
            String message = "查询当前用户基本信息失败，尝试访问的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }

}
